<template>
  <div class="container">
    <div class="app-container">
      <!--角色管理内容-->
      <div class="role-box">
        <el-button @click="showDialog=true" type="primary" size="mini">添加角色</el-button>
      </div>
      <!--表格组件-->
      <el-table :data="list">
        <!--放置列-->
        <el-table-column prop="name" label="角色" align="center" width="200px">
          <template v-slot="{row}">
            <!-- 条件判断-->
            <el-input v-model="row.editRow.name" v-if="row.isEdit" size="mini"></el-input>
            <span v-else>{{ row.name }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="state" label="启用" align="center" width="200px">
          <template v-slot="{ row }">
            <el-switch :active-value="1" :inactive-value="0" v-model="row.editRow.state" v-if="row.isEdit"></el-switch>
            <span v-else> {{ row.state === 1 ? '已启用' : row.state === 0 ? '未启用' : '无' }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="description" label="描述" align="center">
          <template v-slot="{row}">
            <!-- 条件判断-->
            <el-input v-model="row.editRow.description" type="textarea" v-if="row.isEdit" size="mini"></el-input>
            <span v-else>{{ row.description }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center">
          <template v-slot="{row}">
            <template v-if="row.isEdit">
              <!--  编辑状态-->
              <el-button @click="btnConfirm(row)" size="mini" type="primary">确定</el-button>
              <el-button @click="row.isEdit=false" size="mini">取消</el-button>
            </template>
            <template v-else>
              <!-- 非编辑状态-->
              <el-button size="mini" type="text" @click="getPermit(row.id)">分配权限</el-button>
              <el-button size="mini" type="text" @click="editRole(row)">编辑</el-button>
              <el-popconfirm
                title="确定删除吗？"
                @onConfirm="del(row.id)"
              >
                <el-button style="margin-left: 10px" slot="reference" size="mini" type="text">删除</el-button>
              </el-popconfirm>

            </template>
          </template>
        </el-table-column>
      </el-table>
      <!--放置分页组件-->
      <!--el-row可以设置对齐方式-->
      <el-row type="flex" justify="end" align="middle" style="height: 60px">
        <!--放置分页组件-->
        <el-pagination
          @current-change="changPage"
          :current-page="pageParams.page"
          :page-size="pageParams.pageSize"
          layout="prev, pager, next"
          :total="pageParams.total">
        </el-pagination>
      </el-row>
    </div>
    <!--放置弹层-->
    <!--点击叉号也要重置表单，有个close事件可以在点击叉号的时候触发-->
    <el-dialog @close="btnCancel" :visible.sync="showDialog" title="新增角色" width="500px">
      <!--表单内容-->
      <el-form lable-width="120px" :model="roleForm" :rules="roleRules" ref="roleForm">
        <el-form-item label="角色名称" prop="name">
          <el-input v-model="roleForm.name" size="mini" style="width: 300px"></el-input>
        </el-form-item>
        <!--不做校验就不需要写prop属性-->
        <!--重置表单数据需要写prop属性-->
        <el-form-item label="启动" prop="state">
          <el-switch v-model="roleForm.state" :active-value="1" :inactive-value="0"></el-switch>
        </el-form-item>
        <el-form-item label="角色描述" prop="description">
          <el-input v-model="roleForm.description" type="textarea" size="mini" style="width: 300px"></el-input>
        </el-form-item>
        <el-form-item>
          <el-row type="flex" justify="center">
            <el-col :span="12">
              <el-button type="primary" size="mini" @click="btnOk">确定</el-button>
              <el-button size="mini" @click="btnCancel">取消</el-button>
            </el-col>
          </el-row>
        </el-form-item>
      </el-form>
    </el-dialog>

    <!--    放置分配权限的弹层-->
    <el-dialog :visible.sync="showPermit" title="分配权限">
      <el-tree ref="permTree" :data="permitList" :props="defaultProps" :default-checked-keys="permIds" node-key="id" check-strictly show-checkbox default-expand-all>
      </el-tree>
      <el-row slot="footer" type="flex" justify="center">
        <el-col :span="6">
          <el-button size="mini" type="primary" @click="ok">确定</el-button>
          <el-button size="mini" @click="showPermit=false">取消</el-button>
        </el-col>
      </el-row>
    </el-dialog>
  </div>
</template>
<script>
import {getRoleList, addRole, editRole, delRole, getRoleDetail, getRolePermit} from '@/api/role'
import {getPermissionList} from '@/api/permission'
import {toTreeDate} from '@/utils'

export default {
  name: 'Role',
  data() {
    return {
      showDialog: false,
      showPermit: false,
      permitList: [], // 可以的权限列表
      permIds: [], // 数据绑定
      currentId: null, // 分配权限,点击当前用户的id
      defaultProps: {
        label: 'name'
      },
      list: [],
      // 分页信息
      pageParams: {
        page: 1,
        pageSize: 10,
        total: 0
      },
      roleForm: {
        name: '',
        description: '',
        state: 0 // 关闭是0 打开是1
      },
      roleRules: {
        name: [
          {
            required: true,
            message: '角色名称不能为空',
            trigger: 'blur'
          }
        ],
        description: [
          {
            required: true,
            message: '角色描述不能为空',
            trigger: 'blur'
          }
        ]
      }
    }
  },
  created() {
    this.getRoleList()
  },
  methods: {
    async getRoleList() {
      const res = await getRoleList(this.pageParams) // 初始化数据 请求第一页的数据
      this.list = res.rows
      this.pageParams.total = res.total
      // 针对每一行数据添加一个编辑标记
      this.list.forEach(item => {
        // item.isEdit = false // 添加一个属性 初始值为false
        // 数据响应式的问题：数据变化，视图更新；但是添加动态属性 不具备响应式特点
        // this.$set(目标对象,添加/删除的属性名称，属性初始值) 可以针对目标对象 添加的属性 添加响应式
        this.$set(item, 'isEdit', false)
        this.$set(item, 'editRow', {
          name: item.name,
          state: item.state,
          description: item.description
        })
      })
    },
    // 切换分页时 请求最新的数据
    changPage(newPage) {
      this.pageParams.page = newPage // 赋值当前页面（最新的页面）
      this.getRoleList()
    },
    btnOk() {
      this.$refs.roleForm.validate(async isOk => {
        if (isOk) {
          await addRole(this.roleForm)
          this.$message.success('新增角色成功')
          this.getRoleList()
          this.btnCancel()
        }
      })
    },
    btnCancel() {
      this.$refs.roleForm.resetFields()
      this.showDialog = false
    },
    editRole(row) {
      row.isEdit = true
      // 更新缓存数据
      row.editRow.name = row.name
      row.editRow.stare = row.state
      row.editRow.description = row.description
    },
    async del(id) {
      await delRole(id) // 只是删除了后端的数据，前端现在还没变
      this.$message.success('删除角色成功')
      // 如果删除的是最后一个数据
      if (this.list.length === 1 && this.pageParams.page > 1) {
        this.pageParams.page--
      }
      this.getRoleList()
    },
    // 行内编辑确定按钮
    async btnConfirm(row) {
      // 手动校验必填项
      if (row.editRow.name && row.editRow.description) {
        // 接口
        await editRole({
          ...row.editRow,
          id: row.id
        })
        this.$message.success('更新角色成功')
        // 为了规避eslint 误判 row.name=row.editRow.name
        // Object.assign(target,source)  把来源赋值给目标
        Object.assign(row, {
          ...row.editRow,
          isEdit: false // 推出编辑模式
        })
      } else {
        this.$message.warning('角色和描述不能为空')
      }
    },

    // 点击分配权限
    async getPermit(id) {
      this.permitList = toTreeDate(await getPermissionList(), 0)
      this.currentId = id
      const {permIds} = await getRoleDetail(id)
      this.permIds = permIds
      this.showPermit = true
    },
    async ok() {
      await getRolePermit({
        id: this.currentId,
        permIds: this.$refs.permTree.getCheckedKeys() // 之前绑定的是单向 不是双向绑定 所以要拿到最新的ids
      })
      this.$message.success('分配权限成功')
      this.showPermit = false
    }
  }
}
</script>
<style scoped>
.role-box {
  padding: 10px;
}
</style>
